package com.jpcc.vw.onlineRadio.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.RemoteException;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
/*Start by menglingqiang*/
import android.util.Log;
/*End by menglingqiang*/
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.RadioScheduleAdapter;
import com.jpcc.vw.onlineRadio.constants.Constants;
/*Start by menglingqiang*/
import com.jpcc.vw.onlineRadio.application.MusicApplication;
/*End by menglingqiang*/
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.RefreshPlayingAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TransformUtils;
/*Start by menglingqiang*/
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/
import com.orhanobut.logger.Logger;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func2;

/**
 * 点击播放画面的节目列表弹出的专辑画面
 */
public class AlbumProgramsActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.imv_album_cover)
    CircleImageView imv_album_cover;
    @BindView(R.id.tv_album_host)
    TextView tv_album_host;
    @BindView(R.id.recyclerview_tracks)
    ListView recyclerview_tracks;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;
    @BindView(R.id.tv_title)
    TextView tv_title;

    private IRadio radioModel;
    private RadioScheduleAdapter adapter;
    private List<RadioDeailBean.RadioSchedule> datas = new ArrayList<>();
    private long radioId = -1;
    private String radio_name;

    @Override
    public int getLayoutId() {
        return R.layout.activity_radio_detail;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        radioModel = new RadioImpl();
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlbumProgramsActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AlbumProgramsActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
//        for (int index=0;index<10;index++){
//            AlbumProgramTrackEntity entity=new AlbumProgramTrackEntity();
//            datas.add(entity);
//        }
        radioId = getIntent().getLongExtra("key_radio_id", -1);
        radio_name = getIntent().getStringExtra("key_radio_name");
        if(!TextUtils.isEmpty(radio_name)){
            tv_title.setText(radio_name);
        }
        if (radioId == -1) {
            this.finish();
        }
        adapter = new RadioScheduleAdapter(datas, this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
//        recyclerview_tracks.setLayoutManager(manager);
        recyclerview_tracks.setAdapter(adapter);
        recyclerview_tracks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Constants.isRelease) {
                    ConnectivityManager connectivityManager = (ConnectivityManager) AlbumProgramsActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
                    boolean connected = connectivityManager.getNetworkStatus();
                    if (!connected) {
                        if (!TextUtils.isEmpty(datas.get(position).getListenBackUrl())) {
                            ToastUtils.show(R.string.string_88);
                            return;
                        } else if (position > 0 && !TextUtils.isEmpty(datas.get(position - 1).getListenBackUrl()) && TextUtils.isEmpty(datas.get(position).getListenBackUrl())) {
                            ToastUtils.show(R.string.string_88);
                            return;
                        } else {
                            ToastUtils.show(R.string.string_88);
                            return;
                        }
                    }
                }
                if (position > 0 && TextUtils.isEmpty(datas.get(position).getListenBackUrl()) && TextUtils.isEmpty(datas.get(position - 1).getListenBackUrl())) {
                    ToastUtils.show(R.string.string_40);
                    return;
                } else if (position > 0 && TextUtils.isEmpty(datas.get(position).getListenBackUrl()) && !TextUtils.isEmpty(datas.get(position - 1).getListenBackUrl())) {
                    List<Track> tracks = new ArrayList<>();
                    for (int index = 0; index < datas.size(); index++) {
                        if (!TextUtils.isEmpty(datas.get(index).getListenBackUrl())) {
                            RadioDeailBean.RadioSchedule shcedule = datas.get(index);
                            Track track = new Track();
                            track.setId(shcedule.getId());
                            track.setTrackTitle(shcedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                            track.setCoverUrlMiddle(shcedule.getRelatedProgram().getBackPicUrl());
                            track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setPlayUrl32(shcedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radio_name);
                            track.type = "radio";
                            track.setLive(false);
                            track.setAnnouncer(announcer);
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (shcedule.getEndTime().equals("00:00")) {
                                    shcedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(shcedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(shcedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(shcedule.getStartTime());
                            track.setEndString(shcedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);
                            tracks.add(track);
                        }
                    }
                    getListenbackAndLivingProgram(tracks, position, true);
                } else {
                    List<Track> tracks = new ArrayList<>();
                    for (int index = 0; index < datas.size(); index++) {
                        if (!TextUtils.isEmpty(datas.get(index).getListenBackUrl())) {
                            RadioDeailBean.RadioSchedule shcedule = datas.get(index);
                            Track track = new Track();
                            track.setId(shcedule.getId());
                            track.setTrackTitle(shcedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                            track.setCoverUrlMiddle(shcedule.getRelatedProgram().getBackPicUrl());
                            track.setCoverUrlLarge(shcedule.getRelatedProgram().getBackPicUrl());
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setPlayUrl32(shcedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radio_name);
                            track.type = "radio";
                            track.setLive(false);
                            track.setAnnouncer(announcer);
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (shcedule.getEndTime().equals("00:00")) {
                                    shcedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(shcedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(shcedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(shcedule.getStartTime());
                            track.setEndString(shcedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);
                            tracks.add(track);
                        }
                    }
                    getListenbackAndLivingProgram(tracks, position, false);
                }
            }
        });
    }


    private void getListenbackAndLivingProgram(List<Track> sources, int position, boolean isLive) {
        radioModel.GetPlayingProgramDetail(radioId).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
            @Override
            public void onSuccess(LiveRadioDetailBean response) {
                Track liveRadio = new Track();
                if (response.getData() != null) {
//                    LiveRadioDetailBean response = response.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                    Constants.LastModeFlag = false;
                    AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, isLive, position);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(BaseBean response) {

            }
        });
    }

    private void getCurrentPlayingRadioProgram(List<Track> tracks, int position) {

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "DEBUG", null, "GetPlayingProgramDetail request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetPlayingProgramDetail(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).subscribe(new CommonSubscriber<LiveRadioDetailBean>() {
            @Override
            public void onSuccess(LiveRadioDetailBean response) {
                Track track = new Track();
                SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                subordinatedAlbum.setId(radioId);
                subordinatedAlbum.setAlbumTitle(AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumName());
                Announcer announcer = new Announcer();
                announcer.setNickname("");
                track.setId(response.getData().getId());
                track.setTrackTitle(response.getData().getProgramName());
                track.setCoverUrlLarge(response.getData().getBackPicUrl());
                track.setPlayUrl32(response.getData().getRate24AacUrl());
                track.setCanDownload(false);
                track.setDownloadUrl("");
                track.type = "radio";
                track.setSubordinatedAlbum(subordinatedAlbum);
                track.setAnnouncer(announcer);
                track.setLive(true);
                tracks.add(track);
                AlbumRadioAudioPlayer.get().setOnSourcesForListenbackRadio(tracks, position, 4);
                adapter.notifyDataSetChanged();
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetPlayingProgramDetail onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }

            @Override
            public void onFailure(BaseBean response) {
                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "GetPlayingProgramDetail onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
    }

    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    public void onEvent(RefreshPlayingAction action) {
        adapter.notifyDataSetChanged();
    }


    public void onEvent(WaveAction wave) {

        Observable.just("action").observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        int lastDay = 0;
        int thisDay = 0;
        //星期一 获取星期天和星期一的节目单
        if (weekday == 2) {
            lastDay = 0;
            thisDay = 1;
        }
        //星期天 获取星期六和星期天的节目单
        else if (weekday == 1) {
            lastDay = 6;
            thisDay = 0;
        } else {
            lastDay = weekday - 2;
            thisDay = weekday - 1;
        }
        Observable.zip(radioModel.getLiveSchedules(radioId, lastDay), radioModel.getLiveSchedules(radioId, thisDay), new Func2<RadioDeailBean, RadioDeailBean, RadioDeailBean>() {
            @Override
            public RadioDeailBean call(RadioDeailBean radioDeailBean, RadioDeailBean radioDeailBean2) {
                for (RadioDeailBean.RadioSchedule schedule : radioDeailBean.getData()) {
                    schedule.setYestorday(true);
                }
                radioDeailBean.getData().addAll(radioDeailBean2.getData());
                return radioDeailBean;
            }
        }).compose(TransformUtils.<RadioDeailBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
                progress_circular.setVisibility(View.VISIBLE);
            }
        }).subscribe(new CommonSubscriber<RadioDeailBean>() {
            @Override
            public void onSuccess(RadioDeailBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                if (response.getData() != null) {
                    datas.clear();
                    datas.addAll(response.getData());
                    adapter.setDatas(datas);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                ToastUtils.show(response.getStatusMessage());
            }
        });
        //表示星期一
//        if (weekday - 1 == 1) {
//
//            /*Start by menglingqiang*/
//            Date dt = new Date();
//            try {
//                TracelogInterface inter = MusicApplication.getLogInterface();
//                if (inter != null) {
//                    inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "DEBUG", null, "getLiveSchedules request");
//                } else {
//                    Log.e("jgj", "inter == null");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            /*End by menglingqiang*/
//
//            radioModel.getLiveSchedules(radioId, 1).doOnSubscribe(new Action0() {
//                @Override
//                public void call() {
//                    showProgress();
//                }
//            }).subscribe(new CommonSubscriber<RadioDeailBean>() {
//                @Override
//                public void onSuccess(RadioDeailBean response) {
//                    hideProgress();
//                    if (response.getData() != null) {
//                        datas.clear();
//                        datas.addAll(response.getData());
//                        adapter.setDatas(datas);
//                    }
//                    /*Start by menglingqiang*/
//                    Date dt = new Date();
//                    try {
//                        TracelogInterface inter = MusicApplication.getLogInterface();
//                        if (inter != null) {
//                            inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "getLiveSchedules onSuccess");
//                        } else {
//                            Log.e("jgj", "inter == null");
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    /*End by menglingqiang*/
//                }
//
//                @Override
//                public void onFailure(BaseBean response) {
//                    hideProgress();
//                    ToastUtils.show(response.getStatusMessage());
//                    /*Start by menglingqiang*/
//                    Date dt = new Date();
//                    try {
//                        TracelogInterface inter = MusicApplication.getLogInterface();
//                        if (inter != null) {
//                            inter.sendLogData(dt.toString(), dt.toString(), AlbumProgramsActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "getLiveSchedules onFailure");
//                        } else {
//                            Log.e("jgj", "inter == null");
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    /*End by menglingqiang*/
//                }
//            });
//        } else {
//            //表示星期天
//            int weekdayYesterday = weekday - 1;
//            if (weekday - 1 == 0) {
//                weekdayYesterday = 6;
//            } else {
//                weekdayYesterday = weekday - 1;
//            }
//
//            Observable.zip(radioModel.getLiveSchedules(radioId, weekdayYesterday - 1), radioModel.getLiveSchedules(radioId, weekday - 1), new Func2<RadioDeailBean, RadioDeailBean, RadioDeailBean>() {
//                @Override
//                public RadioDeailBean call(RadioDeailBean radioDeailBean, RadioDeailBean radioDeailBean2) {
//                    for (RadioDeailBean.RadioSchedule schedule : radioDeailBean.getData()) {
//                        schedule.setYestorday(true);
//                    }
//                    radioDeailBean.getData().addAll(radioDeailBean2.getData());
//                    return radioDeailBean;
//                }
//            }).compose(TransformUtils.<RadioDeailBean>defaultSchedulers()).doOnSubscribe(new Action0() {
//                @Override
//                public void call() {
//                    showProgress();
//                }
//            }).subscribe(new CommonSubscriber<RadioDeailBean>() {
//                @Override
//                public void onSuccess(RadioDeailBean response) {
//                    hideProgress();
//                    if (response.getData() != null) {
//                        datas.clear();
//                        datas.addAll(response.getData());
//                        adapter.setDatas(datas);
//                    }
//                }
//
//                @Override
//                public void onFailure(BaseBean response) {
//                    hideProgress();
//                    ToastUtils.show(response.getStatusMessage());
//                }
//            });
//        }
    }
}
